/*
 * @Author: Kevin Zhao
 * @Date: 2022-11-06 19:41:48
 * @LastEditTime: 2022-11-06 19:53:23
 * @LastEditors: Kevin Zhao
 * @Description: 
 * @FilePath: \tf-admin\src\pages\Window\useForm.ts
 */
import { ref, reactive, onMounted } from 'vue'
import {
    updateInventoryAPI,
    addInventoryAPI
} from "../../api/inventory";
import { ElMessage } from 'element-plus';

/**
 * @description: 新增/编辑表单
 * @param {Function} query 查询列表方法
 * @return {*}
 */
export default function useForm(query: Function, getInventoryField: Function) {
    // 表单相关
    const dialogVisible = ref(false);
    const formRef = ref();
    const isEdit = ref(false);
    const form = reactive({
        id: '',
        name: '',
        did: '',
        tid: '',
        fid: '',
        basis: '',
        deptDuty: '',
        townDuty: '',
        mainDids: [],
        cooperateDids: [],
    })

    // 新增/编辑 操作
    const handleEdit = (item: any) => {
        // 编辑回填
        if (item) {
            isEdit.value = true;
            form.id = item.id
            form.name = item.name
            form.did = item.did
            form.tid = item.tid
            form.fid = item.fid
            form.basis = item.basis
            form.deptDuty = item.deptDuty
            form.townDuty = item.townDuty
            form.mainDids = item.mainDid.split(',').map(d => d/1)
            form.cooperateDids = item.cooperateDid.split(',').map(d => d/1)

            getInventoryField(form.did);
        }
        // 新增清空
        else {
            isEdit.value = false;
            form.id = ""
            form.name = ""
            form.did = ""
            form.tid = ""
            form.fid = ""
            form.basis = ""
            form.deptDuty = ""
            form.townDuty = ""
            form.mainDids = []
            form.cooperateDids = []
        }

        dialogVisible.value = true;
    };

    // 确定 新增/编辑 操作
    const handleConfirm = () => {
        formRef.value.validate((valid: any, fields: any) => {
            if (valid) {
                let api = isEdit.value ? updateInventoryAPI : addInventoryAPI
                api({ ...form }).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: isEdit.value ? '修改成功' : '新增成功',
                            type: 'success',
                        })
                    }
                    dialogVisible.value = false;
                    query();
                })
            } else {
                console.log('error submit!', fields)
            }
        })
    }

    return {
        dialogVisible,
        formRef,
        isEdit,
        form,
        handleEdit,
        handleConfirm,
    }
}